//
//  WYCOAuthController.m
//  WYCweibo
//
//  Created by 魏云超 on 15/11/21.
//  Copyright © 2015年 魏云超. All rights reserved.
//

#import "WYCOAuthController.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <AFNetworking/AFNetworking.h>
#import "WYCAccount.h"
#import "WYCNewFeatureController.h"
#import "WYCWelcomeController.h"

#define WYC_REQUEST_TOKEN_BASE_URL @"https://api.weibo.com/oauth2/authorize"
#define WYC_CLIENT_ID @"4253113730"
#define WYC_SECRET @"08fb67f842d384e9b866c16e2f3d2cc1"
#define WYC_REDIRECT_URL @"http://www.writediary.cn"
#define WYC_ACCESSTOKEN_URL @"https://api.weibo.com/oauth2/access_token"

@interface WYCOAuthController ()
- (IBAction)close:(id)sender;

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation WYCOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置控制器为代理
    self.webView.delegate = self;
    
    //1.从服务器加载界面
    NSString *str = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",WYC_REQUEST_TOKEN_BASE_URL,WYC_CLIENT_ID,WYC_REDIRECT_URL];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}


- (IBAction)close:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];

}
#pragma mark - webview代理
//webview每次发送请求都调用该方法,返回bool值 如果返回yes代表允许请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //判断即将发送请求的地址中是否包含code,如果包含说明已经验证成功
    NSRange range = [request.URL.absoluteString rangeOfString:@"code="];
    
    if (range.location != NSNotFound) {
        
        NSString *code = [request.URL.query substringFromIndex:@"code=".length];
        //利用code换取accessToken
        [self accessTokenWithCode:code];
        return NO;
    }
    return true;
}
-(void)accessTokenWithCode:(NSString *)code
{
    /*
     client_id	 	申请应用时分配的AppKey。
     client_secret	 申请应用时分配的AppSecret。
     grant_type	 	请求的类型，填写authorization_code
     code	 	    调用authorize获得的code值。
     redirect_uri	 回调地址，需需与注册应用里的回调地址一致。
     */


    //1.封装请求参数
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"client_id"]= WYC_CLIENT_ID;
    parameter[@"client_secret"]= WYC_SECRET;
    parameter[@"grant_type"]= @"authorization_code";
    parameter[@"code"]= code;
    parameter[@"redirect_uri"]= WYC_REDIRECT_URL;
    //2.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置afn能够接受的类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    //3.发送请求
    [manager POST:WYC_ACCESSTOKEN_URL parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        DDLogInfo(@"授权成功");
         DDLogInfo(@"%@",responseObject);
        //3.1 存储授权信息
        //转换成模型数据
        WYCAccount *account = [WYCAccount accountWithDict:responseObject];
        //1.归档数据
        //2.获取沙盒路径
        //3.存储数据
        [account save];
        //4.判断是否是第一次使用软件,或者是升级软件
        [[UIApplication sharedApplication].keyWindow chooseRootViewController];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DDLogInfo(@"授权失败");
        DDLogInfo(@"%@",error);
        [SVProgressHUD showWithStatus:@"请求失败" maskType:SVProgressHUDMaskTypeBlack];
    }];
    
}
//开始加载时
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [SVProgressHUD showWithStatus:@"正在加载中..." maskType:SVProgressHUDMaskTypeBlack];
}
//加载完毕时
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [SVProgressHUD dismiss];
}
//加载错误时
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
    [SVProgressHUD dismiss];
}














@end
